/*
 * @Description: 全宗reducer
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-04-20 15:14:26
 */

import { updateItemById } from '@/utils/list';
import {
  ADD_LEVEL_BY_ID,
  ARC_TYPE_LOADING,
  METADATA_LOADING,
  METADATA_LOADING_FINISH,
  SET_ARC_TYPE_LIST,
  SET_METADATA_LIST
} from '../constants';

export const MetadataConfigReducer = (state, action) => {
  switch (action.type) {
    // 表格加载loading
    case ARC_TYPE_LOADING:
      return { ...state, loading: true };

    /**
     * @description: 加载表格数据及相关数据
     * @param {Array} data 表格数据
     * @return {*}
     */
    case SET_ARC_TYPE_LIST: {
      const ATList = action.data.map((item) => {
        item.treeName = item.atName;
        item.key = item.id;
        return item;
      });
      return {
        ...state,
        ATList
      };
    }

    /**
     * @description: 加载表格数据及相关数据
     * @param {Array} data 表格数据
     * @param {Number} id 档案类型ID
     * @return {*}
     */
    case ADD_LEVEL_BY_ID: {
      const children = action.data.map((item) => {
        item.treeName = item.levelName;
        item.key = `${action.id}-${item.level}`;
        item.isLeaf = true;
        return item;
      });
      return {
        ...state,
        ATList: updateItemById(action.id, { children }, state.ATList)
      };
    }

    // 表格加载loading
    case METADATA_LOADING:
      return { ...state, metadataLoading: true };

    // 表格加载loading 结束
    case METADATA_LOADING_FINISH:
      return { ...state, metadataLoading: false };

    /**
     * @description: 加载元数据列表
     * @param {Array} data 表格数据
     */
    case SET_METADATA_LIST: {
      return {
        ...state,
        metadataList: action.data,
        metadataLoading: false
      };
    }

    default:
      console.log('untouched', action);
      return state;
  }
};
